// 1728000

var superagent = require('superagent');
var fs = require('fs');
var images = require("./models/images");
var eventproxy = require("eventproxy");

var staticInt = 1728000 * 3;

var currentDate = new Date('2016-08-10 8:00:00');
var currentDateInt = Date.parse(currentDate) / 1000;

var queryDic = { 'systemVersion': "10.0", "resolution": "{640, 1136}", "appVersion": "2.0.6", "platform": "iphone", "openUDID": "baddce8cb9ffcee0a3985a5e4d859584d7cfbe36", "page_size": "60" };
queryDic.time = currentDateInt + "";

var requestAllImages = [];

function requestAllImageList(currentDateInt, callback) {
    queryDic.time = currentDateInt + "";
    superagent.get("http://lab.zuimeia.com/wallpaper/category/2/")
        .query(queryDic)
        .end(function (err, res) {
            var dic = JSON.parse(res.text);
            requestAllImages = requestAllImages.concat(dic.data.images);
            if (dic.data.has_next) {
                console.log("还有下一页，当前时间戳 " + currentDateInt);
                requestAllImageList(currentDateInt - staticInt, callback);
            } else {
                console.log("没有下一页，获取数据存储本地数据库");
                images.saveImageArrayToLibrary(requestAllImages, function () {
                    callback(1);
                });
            }
        });
}

function loadAllImagesFromFile(callback) {
    images.findAllImage(function (results) {
        callback(results);
    });
}

exports.requestAllImageList = requestAllImageList;
exports.currentDateInt = currentDateInt;
exports.loadAllImagesFromFile = loadAllImagesFromFile;